#!/usr/bin/python
import sys
import os

# Note to self: just run this with "./autostart -detached -dbstart reuse" for the common
# case of starting a single-node config after a reboot.


logfilename = "./autostart.log"
fh = open(logfilename, 'a')

def log(string):
    """Writes a string to both stdout and the log file"""
    string += "\n"
    fh.write(string)
    sys.stdout.write(string)

logfile = 'autostart.log'
user = 'swiftp-proxy'
erlnodename = 'swiftp_proxy'
erlcookie = 'abc123'
installdir = '/swiftp_proxy'
# The "-mnesia dir" parameter to erl requires some strange quoting
mnesiadir = "\\\"" + installdir + "/mnesia_dir\\\"" 

def main(argv):
    log('Changing directory owner...')
    os.system('chown ' + user + ' ' + installdir + ' -R')

    log('Calling iptables setup script...')

    # Install the iptables rule to forward from port 21 to port 2121, if not installed
    returnval = os.system('iptables -t nat -S PREROUTING | ' \
                        + 'grep -- \'-A PREROUTING -p tcp -m tcp --dport 21 -j REDIRECT --to-ports 2121\'')
    if returnval == 0:
        log("Iptables redirect already in place, taking no action")
    else:
        log("Iptables redirect not in place yet, installing...")
        os.system('iptables -t nat -A PREROUTING -p tcp --dport 21 -j REDIRECT --to-port 2121')
        log("Done installing iptables rule.")

    log("Copying Apache virtualhost config and restarting Apache")
    returnval = os.system('cp ./swiftp_vhost /etc/apache2/sites-enabled/')
    if returnval == 0:
        log("Copied vhost config OK")
        os.system('apache2ctl restart')
    else:
        log("Failed to copy Apache vhost config!")
    
        
    # All command line params not after the first (the script name)
    # should be passed to the erlang server:start/1 function.
    startargs = ""
    if len(argv) > 1:
        for param in argv[1:]:
            startargs += param + ' '

    log('Starting erlang...')


    # Run backgrounded, entry point server:start/0,1
    command = 'su '+user+' -c \'erl ' \
                   + ' -pa ./ebin ' \
                   + ' -name ' + erlnodename \
                   + ' -s swiftp_proxy do_app_start ' \
                   + ' -mnesia dir ' + mnesiadir \
                   + ' -boot start_sasl ' \
                   + ' -config errlogconf ' \
                   + ' -setcookie ' + erlcookie \
                   + ' ' + startargs + ' ' \
                   + '\''
    log("Running start command: " + command)
    os.system(command)
    
if __name__ == '__main__':
    main(sys.argv)


